<template>
	<!-- 工时补填 -->
	<view>
		<!-- 固定部分 -->
		<u-sticky bgColor="#fff" :style="{paddingTop:marginTopBot + 'px'}" :customNavHeight="stickyIptTop">
			<realTimeInput @inputDataChangeHandler="inputDataChangeHandler" v-model="iptVal"
				@itemClick="clickWorkingHours" :lastWeekWorkingHours="lastWeekWorkingHours"/>
			<uni-notice-bar style="margin-bottom: 0;text-align: center;" color="#000" background-color="#ffff80" single
				:text="noticeText" />
				<!-- `已补填工时：${sum}(小时)，剩余可补填工时：${Math.max(remain,0)}(小时)` -->
		</u-sticky>

		<!-- 主体部分 -->
		<!-- 因为底部的按钮占了50px所以要设置padding-bottom,设置margin-bottom无效 -->
		<!-- 因为不知道哪里设置了样式穿透，设置的scoped无效，所以只能用文件名加名称来命名class -->
		<view class="submit_this_week-main-content">
			<!-- 根据状态来判断选择哪个作为插槽内容 -->
			<view v-for="(item,index) in showTotalData.workingHoursDetailedList" :key="index">
				<taskTimeMainContentVue :isLastWeek="true" :totalData="showTotalData.workingHoursDetailedList[index]">
					<!-- 展示步进器 -->
					<u-number-box v-if="showStepNumber" decimalLength="1" :min="0" :max="total" :step="0.1"
						v-model="showTotalData.workingHoursDetailedList[index].fillHours" @change="valChange($event.value,item)">
						<h-number-input slot="input" inputAlign="center" border="none" :customStyle="{
								padding: 0,
								height: '30px',
								width: '35px',
								borderRadius: '0',
								backgroundColor: '#EBECEE',
								margin: '0 2px'
								}" :defaultNumber="0" :min="0" :max="total" v-model="showTotalData.workingHoursDetailedList[index].fillHours"
							@change="valChange($event,item)" placeholderStyle="color: #EBECEE"></h-number-input>
					</u-number-box>
					<!-- 展示文本 -->
					<span v-else>{{showTotalData.workingHoursDetailedList[index].fillHours||0}}</span>
				</taskTimeMainContentVue>
			</view>
		</view>

		<!-- 固定在底部的按钮 -->
		<fixedBottomButtonsVue :showSaveBtn='showSaveBtn' :avoidRepeatSubmitFlag="avoidRepeatSubmitFlag" :backPath="backPath">
			<!-- 根据页面状态判断是否显示撤回按钮,后续如果有逻辑改变，可以考虑将相同逻辑的做成computed -->
			<u-button v-if="showReturn" type="primary" text="返回" @click="backStep"></u-button>
			<u-button v-else type="primary" text="保存" @click="saveTo"></u-button>
			<u-button v-if="!showReturn" :disabled="avoidRepeatSubmitFlag" type="primary" text="提交" @click="clickSubmit"></u-button>
		</fixedBottomButtonsVue>

	</view>
</template>

<!-- 接口很多复用的,所以没修改调用的名字 -->
<script>
	import realTimeInput from "@/components/real-time-input/realTimeInput"
	import taskTimeMainContentVue from "./components/taskTimeMainContent.vue"
	import fixedBottomButtonsVue from "@/components/fixed-bottom-buttons/fixedBottomButtons.vue"
	// 用来做工时的加减，js原生的不够精确
	// 将数据转成new Decimal(数据),然后用Decimal库的方法做加减或者判断，不能用js原生的方法
	import Decimal from "decimal.js"
	
	import moment from 'moment'
	import 'moment/locale/zh-cn' // 引入中文语言包
	// 设置语言环境为中文
	moment.locale('zh-cn')
	import {
		getNotFillThisWeekMainData,
		getNotFillThisWeekTaskData,
		getFilledThisWeekMainData,
		getFilledThisWeekTaskData,
		// 本周未撤回，提交本周数据
		addNotFillThisWeekFormData,
		// 撤回本周数据
		revokeThisWeekFormData,
		// 提交撤回过的本周数据
		addRevokeThisWeekFormData,
		queryHisWorkingHours,
		allSubmitUrl,
		generatedFormNumber
	} from '@/api/taskInput/index.js'
	
	export default {
		name: 'submitLastWeekTaskTime',
		components: {
			realTimeInput,
			taskTimeMainContentVue,
			fixedBottomButtonsVue
		},
		data() {
			return {
				iptVal: '',
				safeArea: 0,
				stickyIptTop: 44,
				marginTopBot: 10,
				backPath: '/pages/home/home',
				sum: 0,
				total: 8,
				showStepNumber: false,
				showRevokeBtn: true,
				// 进入页面时是查看还是补填
				status: '',
				// 用户是生产统筹人员还是普通人员
				userType: '',
				// 主表数据
				mainData: {},
				// 任务表数据,也就是子表数据
				taskData: [],
				// 合并主表和子表的数据,用来传输给后端
				totalData: {},
				// 仅用作展示的全部的数据,用来做前端筛选
				showTotalData: {},
				// 避免重复点击提交按钮
				avoidRepeatSubmitFlag: false,
				// 是否展示保存按钮
				showSaveBtn: true,
				// 是否展示返回按钮
				showReturn: false,
				lastWeekWorkingHours: [],//以前投入的工时列表
				nowClickParams: {},//当前点击item数据
			}
		},
		computed: {
			// 剩余时间
			remain() {
				return new Decimal(this.total).minus(new Decimal(this.sum))
			},
			noticeText(){
				if(this.status === 'fillLastWeek'){
				return `已补填工时：${this.sum}(小时)，剩余可补填工时：${Math.max(this.remain,0)}(小时)`
				}else{
				return `补填工时：${this.sum}(小时)`
				}
			}
		},
		watch: {
			status: {
				async handler(val) {
					let _mainData
					let _taskData
					// 设置初始状态，根据status来判断是否设置fillInTime
					await this.setInitData()
					switch (val) {
						// 上周未填写
						case 'fillLastWeek':
							// 上周的查看，补填和本周的撤回后补填是同样的接口，只是参数不同
							// _mainData = await getFilledThisWeekMainData({ fillInType: 'miss' })
							// 得到主表数据，和addNotFilled的数据结构不同
							// this.mainData = _mainData.result.records[0]
							
							this.hisWorkingHoursMethod('')
							
							// 展示步进器
							this.showStepNumber = true
							// 不展示撤回按钮
							this.showRevokeBtn = false
							// 不展示返回按钮
							this.showReturn = false
							break;
							// 上周已填写,查看上周数据
						case 'viewLastWeek':
						
							this.hisWorkingHoursMethod('miss')
						
							// // 主表查询参数
							// _mainData = await getFilledThisWeekMainData({ fillInType: 'miss' })
							// // 得到主表数据，和addNotFilled的数据结构不同
							// this.mainData = _mainData.result.records[0]
							// // 同上面
							// _taskData = await getFilledThisWeekTaskData({
							// 	workId: this.mainData.id,
							// 	pageNo: 1,
							// 	pageSize: -1
							// })
							// this.taskData = _taskData.result.records
							// this.totalData = {
							// 	...this.mainData,
							// 	...this.totalData
							// }
							// this.totalData.workingHoursDetailedList = this.taskData
							// this.showTotalData = JSON.parse(JSON.stringify(this.totalData))
							// this.calculateSum()
							// this.noticeText = `上周补填工时：${this.sum}(小时)`
							// 不展示步进器，只展示数据
							this.showStepNumber = false
							// 展示撤回按钮
							this.showRevokeBtn = false
							// 不展示保存按钮
							this.showSaveBtn = false
							// 展示返回按钮
							this.showReturn = true
							break;
							// 撤回重填，接口大体类似查看

						default:
							break;
					}
				}
			}
		},

		// 从首页获取来的数据
		onLoad(obj) {
			this.status = obj.iptStatus
			this.userType = obj.userType
		},
		created() {
			uni.getSystemInfo({
				success(e) {
					uni.setStorageSync('getSystemInfo', e);
				}
			})
			this.safeArea = uni.getStorageSync('getSystemInfo').safeArea.top
			this.stickyIptTop = this.safeArea + 44
			// #ifdef APP-PLUS
			this.stickyIptTop = 0
			// #endif
		},
		methods: {
			// 设置fillInTime
			async setInitData() {
				// 获取单据编号
				const _res = await generatedFormNumber({ type: 'miss' })
				_res && this.$set(this.totalData, 'billNo', _res)
				if (this.status === 'fillLastWeek') {
					this.$set(this.totalData, 'fillInTime', moment().format('YYYY-MM-DD HH:mm:ss'))
				}
			},
			// 工时填报-补填查询日表
			async hisWorkingHoursMethod(fillInType) {
			  let res = null
			  let resultList = null
			  /* 是查看补填历史 */
			  if(fillInType==='miss'){
				res = await getFilledThisWeekMainData({ fillInType })
			  }else{
				res = await queryHisWorkingHours()
			  }
			  
			  if (res.success) {
				/* fillInStatus：yes:已填报，no:未填报
				 */
				resultList = fillInType ? res.result.records : res.result
				this.lastWeekWorkingHours = resultList.map(r=>{
				  delete r.billNo
				  delete r.fillInTime
				  return {
					...r,
					billNo: this.totalData.billNo,
					fillInTime: this.totalData.fillInTime,
					isClick: this.nowClickParams.id === r.id ? true : false,
					nowDate: moment(r.vestingDay).format('MMMDD日'), //当前日期
					nowWeek: moment(r.vestingDay).format('dddd') //当前星期
				  }
				})
				/* 首次进来未点击,赋值给第一个 */
				if(JSON.stringify(this.nowClickParams) === '{}'){
				  this.clickWorkingHours(this.lastWeekWorkingHours[0])
				}
			  }else{
				this.$utils.toast(res.message)
			  }
			},
			// 点击切换工时
			clickWorkingHours(item){
				this.nowClickParams = {...item}
				this.lastWeekWorkingHours.forEach(it=>{
				if(item.id==it.id){
				  item.isClick = true
				}else{
				  it.isClick = false
				}
				})
				this.total = 8 
				this.loadData(item)
			},
			loadData(item){
				uni.showLoading({
					title:'加载中...',
					mask:false
				})
				getFilledThisWeekTaskData({
					workId: item.id,
					pageNo: 1,
					pageSize: -1
					
				}).then(res => {
					if(res.success){
						this.taskData = res.result.records
						this.totalData = {
							...this.mainData,
							...this.totalData
						}
						// 合并数据
						this.totalData.workingHoursDetailedList = this.taskData
						this.showTotalData = JSON.parse(JSON.stringify(this.totalData))
						if(this.status==='viewLastWeek'){
							this.calculateSum()
						}
						
					}
				}).finally(()=>{
					uni.hideLoading()
				})
				
			},
			/* 补填保存当前数据 */
			saveTo(){
			  /* 判断是否符合条件 */
			  if(this.judgeCanSubmit(this.nowClickParams.userType)){
				let params = {
				  ...this.nowClickParams,
				  workingHoursDetailedList: this.totalData.workingHoursDetailedList
				}
				delete params.fillInStatus
				params.alearyFillButUnStatic = 'yes'
				addRevokeThisWeekFormData(params).then((res) => {
				  if (res.success) {
					this.$utils.toast('保存成功')
					this.hisWorkingHoursMethod('')
				  } else {
					this.$utils.toast(res.message)
				  }
				})
			  }
			},

			// 返回上一级目录
			backStep() {
				uni.reLaunch({
					url: this.backPath
				})
			},

			// 计算总数
			calculateSum(e) {
				this.sum = new Decimal(0)
				for (let item of this.totalData.workingHoursDetailedList) {
					this.sum = this.sum.add(new Decimal(item.fillHours || 0))
				}
			},

			// 触发步进器数据更新
			valChange(e, item) {
				// 这里的更新会慢，所以用下面这个，获取到更新后的再去做计算
				// 包含前端筛选
				this.$nextTick(() => {
					let _tItem = this.totalData.workingHoursDetailedList.find(tItem => {
						return tItem.projectTaskId === item.projectTaskId
					})
					_tItem.fillHours = e
					// 前端去重
					let comArr = [...this.totalData.workingHoursDetailedList, ...this.showTotalData.workingHoursDetailedList]
					this.totalData.workingHoursDetailedList = this.$utils.uniqueByKey(comArr, 'projectTaskId')
					this.calculateSum(e)
				})
			},

			// 提交补充记录
			async clickSubmit() {
				/* 历史总的补填提交 */
				let statusList = this.lastWeekWorkingHours.map(r=>r.alearyFillButUnStatic)
				/* 判断是否有未填的 */
				if(statusList.includes('no')){
				  let msgDate = this.lastWeekWorkingHours.filter(r=>r.alearyFillButUnStatic==='no').map(r=>r.vestingDay)
				  this.$utils.toast(`请完成${String(msgDate)}工时补填`)
				  this.$emit('canClickSubmit')
				  return
				}
				this.confirmLoading = true
				let ids = this.lastWeekWorkingHours.map(r=>r.id)
				let params = {
				  workIds: String(ids)
				}
				// 禁止重复点击提交
				this.avoidRepeatSubmitFlag = true
				// 补填的提交
				let res = await allSubmitUrl(params).then((res) => {
				  if (res.success) {
					
					this.$utils.uniDlgCallBack({
						title: '提示',
						showCancel: false,
						content: '工时补填成功',
						success: ()=>{
							this.avoidRepeatSubmitFlag = false
							this.backStep()
						}
					})
					
				  } else {
					this.$utils.toast(res.message)
				  }
				}).finally(() => {
					this.avoidRepeatSubmitFlag = false
				})
			},
			// 校验是否符合提交要求
			judgeCanSubmit(type) {
			  const _sum = new Decimal(this.sum)
			  const _total = new Decimal(this.total)
			  if (_sum.equals(_total)) {
				return true
			  } else if (_sum.lessThan(_total)) {
				
				if(type === 'white'){
					this.$utils.toast('白名单人员不用填写!')
					return false
				}
					
				if(type === 'coordinator'){
					this.$utils.toast(`当前工时之和必须等于${this.total}小时才可提交`)
					return false
				}
					
				if(type === 'product_coordinator' || type === 'r_and_d_coordinator'){
					/* 生产/研发统筹人员，工时可小于或等于8小时 */
					return true
				}
				this.$utils.toast(`当前工时之和小于${this.total}小时，不可提交`)
				return false
			  } else {
				this.$utils.toast(`当前工时之和大于${this.total}小时，不可提交`)
				return false
			  }
			},
			// 监听输入框事件
			async inputDataChangeHandler(value) {
				this.iptVal = value
				this.showTotalData.workingHoursDetailedList = this.totalData.workingHoursDetailedList.filter(item => {
					return item.projectName.indexOf(this.iptVal) != -1
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.task-time-submit {
		position: fixed;
		top: 0;
		left: 0;
		background-color: rgb(30, 111, 255);
		color: rgb(255, 255, 255);
		padding: 7px 6px;
		width: 100%;
		z-index: 998;
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;

		.uni-page-head__title {
			font-size: 16px;
			font-weight: 700;
			line-height: 30px;
			text-align: center;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			max-width: 260px;
		}
	}

	.submit_this_week-main-content {
		background: #f2f2f2;
		padding-bottom: 50px;
	}
</style>